<template>
  <div>
    <!--数据源-->
    <transition name="el-fade-in-linear">
      <div class="module" style="margin:15px;" v-show="!isDetailPage">
        <div class="itemTitle">数据源
          <div class="fr itemTitleBtn pr">
            <el-button type="primary" plain size="mini" @click="addJdbcConfigs">增加</el-button>
            <el-button type="danger" plain size="mini">删除</el-button>
          </div>
        </div>
        <el-table border ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange" v-loading="jdbcConfigsLoading">
          <el-table-column type="selection"width="55"></el-table-column>
          <el-table-column prop="dsName" label="数据库名称" width="150" fixed="left"></el-table-column>
          <el-table-column prop="dsType" label="数据库类型" width="100" align="center"></el-table-column>
          <el-table-column prop="dsDesc" label="数据库说明" show-overflow-tooltip></el-table-column>
          <el-table-column prop="dict" label="数据字典文件" width="150"></el-table-column>
          <el-table-column prop="dictSubjects" label="已关联主题词典" :formatter="formatterSubject"></el-table-column>
          <!--<el-table-column prop="ontologyId" label="本体URI标识" width="120"></el-table-column>-->
          <el-table-column prop="classificationState" label="分类分级状态" width="100" align="center">
            <template slot-scope="scope">
              <p style="color:#8c939d" v-if="scope.row.classificationState=='notstart'">未开始</p>
              <p style="color:#F56C6C" v-else-if="scope.row.classificationState=='classifying'||scope.row.classificationState=='classified'">分类中</p>
              <p style="color:#F56C6C" v-else-if="scope.row.classificationState=='evaluating'">评价中</p>
              <p style="color:#F56C6C" v-else-if="scope.row.classificationState=='grading'||scope.row.classificationState=='graded'">分级中</p>
              <p style="color:#409EFF" v-else-if="scope.row.classificationState=='finished'">已完成</p>
            </template>
          </el-table-column>
          <el-table-column prop="classificationTime" label="执行时间" width="150"></el-table-column>
          <!--<el-table-column prop="dsDriver" label="数据库驱动配置" width="120"></el-table-column>-->
          <!--<el-table-column prop="dsUrl" label="JDBC连接URL配置" width="140"></el-table-column>-->
          <!--<el-table-column prop="dsUsername" label="数据库用户名" width="120"></el-table-column>-->
          <!--<el-table-column prop="dsPassword" label="数据库密码" width="120"></el-table-column>-->
          <el-table-column label="操作" width="200px" fixed="right">
            <template slot-scope="scope">
              <el-link icon="el-icon-edit" :underline="false" type="primary" style="margin-right:10px;" @click="editJdbcConfigs(scope.row)">编辑</el-link>
              <el-link icon="el-icon-delete" :underline="false" type="danger" style="margin-right:10px;" @click="delJdbcConfigs(scope.row.id)">删除</el-link>
              <el-link icon="el-icon-view" :underline="false" type="primary" @click="goDetail(scope.row)">分类分级</el-link>
            </template>
          </el-table-column>
        </el-table>
        <div class="fc" style="margin-bottom:15px;margin-top:10px;">
          <el-pagination class="fr" background layout="total, prev, pager, next" :total="jdbcConfigsTotalCount" :page-size="jdbcConfigsPageSize" @current-change="changeJdbcConfigsPage"></el-pagination>
        </div>
      </div>
    </transition>
    <!--数据源详情-->
    <transition name="el-fade-in-linear">
      <div style="margin:15px;" v-show="isDetailPage">
        <div class="module">
          <el-page-header @back="goBack" :content="detailName"></el-page-header>
          <!--分级分类过程-->
          <el-collapse v-model="activeNames" style="margin-top:15px;">
            <el-collapse-item title="分类分级过程" name="1">
              <el-steps :active="jdbcconfigIdStatesNumber" align-center>
                <el-step title="开始">
                  <template slot="description">
                    <el-button type="primary" style="margin-top: 10px" plain size="mini" v-show="jdbcconfigIdStates=='notstart'" @click="submitStates('beginClassification')">开始分类</el-button>
                  </template>
                </el-step>
                <el-step title="分类">
                  <template slot="description">
                    <p v-show="jdbcconfigIdStates=='notstart'">等待执行</p>
                    <p v-show="jdbcconfigIdStates=='classifying'">自动分类中</p>
                    <p v-show="jdbcconfigIdStates=='classified'">自动分类已完成</p>
                    <el-button v-show="jdbcconfigIdStates=='classified'" type="primary" style="margin-top: 10px" plain size="mini" @click="submitStates('finishClassification')">完成分类</el-button>
                    <p v-show="jdbcconfigIdStates=='evaluating' || jdbcconfigIdStates=='grading' || jdbcconfigIdStates=='graded' || jdbcconfigIdStates=='finished'">分类已完成</p>
                  </template>
                </el-step>
                <el-step title="评价">
                  <template slot="description">
                    <p v-show="jdbcconfigIdStates=='notstart' || jdbcconfigIdStates=='classifying' || jdbcconfigIdStates=='classified'">等待执行</p>
                    <p v-show="jdbcconfigIdStates=='evaluating'">请选择业务类别进行评价</p>
                    <el-button v-show="jdbcconfigIdStates=='evaluating'" type="primary" style="margin-top: 10px" plain size="mini" @click="submitStates('finishEvaluation')">完成评价</el-button>
                    <p v-show="jdbcconfigIdStates=='grading' || jdbcconfigIdStates=='graded' || jdbcconfigIdStates=='finished'">评价已完成</p>
                  </template>
                </el-step>
                <el-step title="分级">
                  <template slot="description">
                    <p v-show="jdbcconfigIdStates=='notstart' || jdbcconfigIdStates=='classifying' || jdbcconfigIdStates=='classified' || jdbcconfigIdStates=='evaluating'">等待执行</p>
                    <p v-show="jdbcconfigIdStates=='grading'">自动分级中</p>
                    <p v-show="jdbcconfigIdStates=='graded'">自动分级已完成</p>
                    <el-button v-show="jdbcconfigIdStates=='graded'" type="primary" style="margin-top: 10px" plain size="mini" @click="submitStates('finishGrading')">完成分级</el-button>
                    <p v-show="jdbcconfigIdStates=='finished'">分级已完成</p>
                  </template>
                </el-step>
                <el-step title="完成">
                  <template slot="description">
                    <p v-show="jdbcconfigIdStates=='finished'">{{jdbcconfigIdClassificationTime}}</p>
                  </template>
                </el-step>
              </el-steps>
            </el-collapse-item>
          </el-collapse>
        </div>
        <el-container>
          <el-main class="module">
            <el-container>
              <!--数据分类-->
              <el-aside width="230px" style="border-right:1px solid #EBEEF5">
                <div class="fc">
                  <p style="font-size:13px;border-bottom:1px solid rgb(220, 223, 230);padding-bottom:10px;margin-bottom:5px;">数据分类
                    <span class="fr" style="margin-right: 5px;margin-left:10px;">
                      <el-dropdown trigger="click" @command="selectInstancesType">
                        <span class="el-dropdown-link" style="cursor: pointer;">
                          添加<i class="el-icon-arrow-down el-icon--right"></i>
                        </span>
                        <el-dropdown-menu slot="dropdown">
                          <el-dropdown-item command="subject">主题</el-dropdown-item>
                          <el-dropdown-item command="category">分类</el-dropdown-item>
                        </el-dropdown-menu>
                      </el-dropdown>
                      <!--<el-link icon="el-icon-plus" :underline="false" type="primary" @click="addInstances">添加</el-link>-->
                    </span>
                    <el-link type="primary" :underline="false" icon="el-icon-folder-opened" @click="collapseAll" v-if="isOpenAll"></el-link>
                    <el-link type="primary" :underline="false" icon="el-icon-folder" @click="unFoldAll" v-else></el-link>
                  </p>
                </div>
                <div style="height:700px;overflow: auto;">
                  <el-tree ref="instancesTree" :data="instancesTree" node-key="id" default-expand-all
                           :expand-on-click-node="false"
                           :highlight-current="true"
                           @current-change="changeCurInstances"
                           draggable
                           :allow-drag="allowDragInstances"
                           :allow-drop="allowDropInstances"
                           @node-drop="nodeDropInstances">
                    <span class="custom-tree-node el-tree-node__label" slot-scope="{ node, instancesTree }">
                      <span class="el-tree-node__label">{{ node.data.desc }}</span>
                      <span v-show="node.data.type&&node.data.type!='Entity'">
                        <i class="el-icon-edit" @click="editInstances(node)" style="margin-right:5px;"></i>
                        <i class="el-icon-delete" @click="delInstances(node.data)" v-show="!node.data.children"></i>
                      </span>
                    </span>
                  </el-tree>
                </div>
              </el-aside>
              <!--echarts树图-->
              <el-main>
                <div id="treeEchart" style="height:700px;"></div>
              </el-main>
              <!--问卷-->
              <el-aside width="300px" class="questionnaireWrapper">
                <div class="fc">
                  <p style="font-size:13px;border-bottom:1px solid rgb(220, 223, 230);padding-bottom:10px;">数据分级</p>
                </div>
                <div style="max-height:700px;overflow-x:hidden;margin-top: 10px;">
                  <el-steps direction="vertical" class="questionnaire" :active="questionnaireList.length">
                    <el-step v-for="(item, index) in questionnaireList" :key="index">
                      <template slot="title">
                        <p class="questionnaireTitle" @click="questionnaireIsOpen(index)" v-if="item.type=='indicator'">
                          {{item.indicatorDimensionName}}
                          <i class="el-icon-arrow-down fr" v-if="item.isOpen"></i>
                          <i class="el-icon-arrow-right fr" v-else></i>
                        </p>
                        <p class="questionnaireTitle" v-else>{{item.indicatorDimensionName}}</p>
                      </template>
                      <template slot="description" >
                        <div v-if="item.type=='indicator'">
                          <div class="questionnaireItem" v-show="item.isOpen" :style="item.isOpen?'':'height:0px'">
                            <div v-for="(subItem, subIndex) in item.children" :key="subIndex">
                              <p>{{subIndex+1}}、{{subItem.indicatorName}}</p>
                              <div class="questionnaireRadio" >
                                <el-radio v-for="(radioItem, radioIndex) in subItem.indicatorValue" :key="radioIndex" v-model="propertiesSubmitData[subItem.indicatorCode]" :label="radioItem">{{radioItem}}</el-radio>
                              </div>
                            </div>
                          </div>
                          <div class="questionnaireItemSummary fc" v-if="item.summaryList">
                            <div class="fl" style="width:40px;">总结:</div>
                            <div class="fl">
                              <el-radio v-model="propertiesSubmitData[item.indicatorDimension]" :label="subRadioItem" v-for="(subRadioItem, subRadioIndex) in item.summaryList" :key="subRadioIndex">{{subRadioItem}}</el-radio>
                            </div>
                          </div>
                        </div>
                        <div class="questionnaireRadio" v-else>
                          <el-radio v-model="propertiesSubmitData[item.indicatorDimension]" :label="subItem.levelName" v-for="(subItem, subIndex) in item.summaryList" :key="subIndex">{{subItem.levelName}}</el-radio>
                        </div>
                      </template>
                    </el-step>
                  </el-steps>
                  <div class="textCenter">
                    <el-button type="primary" size="small" style="width:200px;margin:10px auto 0px;" @click="submitProperties">保存</el-button>
                  </div>
                </div>
              </el-aside>
            </el-container>
          </el-main>
        </el-container>
      </div>
    </transition>
    <!--数据源form表单-->
    <el-dialog :title="jdbcConfigsFormTitle" :visible.sync="jdbcConfigsFormVisible" width="600px">
      <el-form :model="jdbcConfigsForm" :rules="jdbcConfigsRules" ref="jdbcConfigs" label-width="140px">
        <el-form-item label="数据源名称" prop="dsName">
          <el-input v-model="jdbcConfigsForm.dsName" autocomplete="off" size="mini"></el-input>
        </el-form-item>
        <el-form-item label="数据源类型" prop="dsType">
          <el-select v-model="jdbcConfigsForm.dsType" placeholder="请选择" size="mini" style="width: 100%">
            <el-option v-for="(item, index) in dsTypeList" :key="index" :label="item.name" :value="item.val"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据库驱动配置" prop="dsDriver">
          <el-input v-model="jdbcConfigsForm.dsDriver" autocomplete="off" size="mini"></el-input>
        </el-form-item>
        <el-form-item label="JDBC连接URL配置" prop="dsUrl">
          <el-input v-model="jdbcConfigsForm.dsUrl" autocomplete="off" size="mini"></el-input>
        </el-form-item>
        <el-form-item label="数据库用户名" prop="dsUsername">
          <el-input v-model="jdbcConfigsForm.dsUsername" autocomplete="off" size="mini"></el-input>
        </el-form-item>
        <el-form-item label="数据库密码" prop="dsPassword">
          <el-input v-model="jdbcConfigsForm.dsPassword" autocomplete="off" size="mini"></el-input>
        </el-form-item>
        <el-form-item label="关联词典配置" prop="dictSubjects">
          <el-cascader :options="subjectTree" :props="{ multiple: true}" clearable :show-all-levels="false" v-model="jdbcConfigsForm.dictSubjects" size="mini" style="width: 100%"></el-cascader>
        </el-form-item>
        <el-form-item label="数据源描述">
          <el-input type="textarea" v-model="jdbcConfigsForm.dsDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="testConnection" size="mini">测试连接</el-button>
        <el-button type="primary" @click="submitJdbcConfigs(false)" size="mini">确 定</el-button>
        <el-button @click="jdbcConfigsFormVisible = false" size="mini">取 消</el-button>
      </div>
    </el-dialog>
    <!--数据分类form表单-->
    <el-dialog :title="instancesFormTitle" :visible.sync="instancesFormVisible" width="350px">
      <el-form :model="instancesForm" :rules="jdbcConfigsRules" ref="instances" label-width="80px">
        <el-form-item label="所属主题" v-if="instancesForm.parentName">
          <el-input v-model="instancesForm.parentName" autocomplete="off" size="mini" disabled=""></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="instanceName">
          <el-input v-model="instancesForm.instanceName" autocomplete="off" size="mini"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="instancesFormVisible = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="submitInstances(false)" size="mini">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Classification",
  data () {
    return {
      isDetailPage: false, // 是否是详情页
      detailName: '', // 详情标题
      activeNames: '1',
      instancesTree: [], // -------------------------------数据分类
      instancesFormTitle: '添加业务分类',
      instancesFormVisible: false,
      instancesForm: {
        id: '',
        instanceName: '',
        className: '',
        parentId: '',
        parentName: ''
      },
      instancesRules: [
        {instanceName: {required: true, message: '请输入名称', trigger: 'blur'}}
      ],
      curInstancesNode: null,
      isOpenAll: true, // 树是否全部展开
      // curInstancesID: '',
      subjectTree: [ // -----------------------------------主题管理
        {value: 'business', label: '业务主题', children: []},
        {value: 'sensitive', label: '敏感主题', children: []}
      ],
      tableData: [], // -----------------------------------数据源
      jdbcConfigsTotalCount: 0,
      jdbcConfigsPageSize: 10,
      jdbcConfigsSort: 'desc',
      jdbcConfigsFormVisible: false,
      jdbcConfigsFormTitle: '添加数据源',
      jdbcConfigsForm: {
        id: '',
        dsName: '',
        dsDesc: '',
        dsType: '',
        dsDriver: '',
        dsUrl: '',
        dsUsername: '',
        dsPassword: '',
        dictSubjects: []
      },
      jdbcConfigsRules: {
        dsName: {required: true, message: '请输入数据库名称', trigger: 'blur'},
        dsType: {required: true, message: '请选择数据库类型', trigger: 'blur'}
      },
      dsTypeList: [
        {name: 'MySQL', val: 'MySQL'},
        {name: 'Oracle', val: 'Oracle'},
        {name: 'SqlServer', val: 'SqlServer'}
      ],
      jdbcConfigsLoading: false,
      fullScreenLoading: null, // 显示加载中
      multipleSelection: [],
      // radio: 1,
      questionnaireList: [],
      jdbcconfigId: '',
      jdbcconfigIdStates: '', // 分级分类状态 notstart：未开始，classifying：自动分类中，classified：自动分类完，evaluating：评价中，grading：自动分级中，graded：自动分级完，finished：已完成
      jdbcconfigIdStatesNumber: 0, // 当前激活的状态
      jdbcconfigIdStatesTimer: null,
      jdbcconfigIdClassificationTime: '',
      propertiesSubmitData: {}, // ---------------数据分级
      isSubmitProperties: false // 是否提交过数据
    }
  },
  created () {
    this.getSubject('subjectType')
    this.getJdbcConfigs(1, this.jdbcConfigsPageSize, this.jdbcConfigsSort)
  },
  beforeDestroy () {
    clearTimeout(this.jdbcconfigIdStatesTimer)
  },
  methods: {
    /*
    * 获取主题
    * */
    getSubject (sort) {
      this.axios.get('/dictsubjects?getType=all&sort=' + sort).then(res => {
        if (res.status === 200) {
          // 置空
          this.subjectTree.map(val => {
            val.children = []
          })
          res.data.map((item, index) => {
            let findIndex = this.subjectTree.findIndex(v => v.value === item.subjectType)
            if (findIndex !== -1) {
              item.value = item.id
              item.label = item.subjectName
              this.subjectTree[findIndex].children.push(item)
            }
          })
        } else {
          this.$commonFunc.message({type: 'error', message: res.statusText})
        }
      })
    },
    /*
    * 获取数据源
    * 参数 pageNum 页码， pageSize 页大小， sort 排序（column,desc）
    * */
    getJdbcConfigs (pageNum, pageSize, sort) {
      this.jdbcConfigsLoading = true
      this.axios.get('/jdbcconfigs?getType=page&pageNum=' + pageNum + '&pageSize=' + pageSize + '&sort=' + sort).then(res => {
        this.jdbcConfigsLoading = false
        if (res.status === 200) {
          this.tableData = res.data.content
          this.jdbcConfigsTotalCount = res.data.totalElements
        } else {
          this.$commonFunc.message({type: 'error', message: res.statusText})
        }
      })
    },
    changeJdbcConfigsPage (page) {
      this.getJdbcConfigs(page, this.jdbcConfigsPageSize, this.jdbcConfigsSort)
    },
    addJdbcConfigs () {
      if (this.$refs.jdbcConfigs) {
        this.$refs.jdbcConfigs.resetFields()
      }
      this.jdbcConfigsFormTitle = '添加数据源'
      this.jdbcConfigsForm.id = ''
      this.jdbcConfigsForm.dsName = ''
      this.jdbcConfigsForm.dsDesc = ''
      this.jdbcConfigsForm.dsType = ''
      this.jdbcConfigsForm.dsDriver = ''
      this.jdbcConfigsForm.dsUrl = ''
      this.jdbcConfigsForm.dsUsername = ''
      this.jdbcConfigsForm.dsPassword = ''
      this.jdbcConfigsForm.dictSubjects = []
      this.jdbcConfigsFormVisible = true
    },
    editJdbcConfigs (row) {
      if (this.$refs.jdbcConfigs) {
        this.$refs.jdbcConfigs.resetFields()
      }
      this.jdbcConfigsFormTitle = '编辑数据源'
      this.jdbcConfigsForm = row
      // this.jdbcConfigsForm.id = row.id
      // this.jdbcConfigsForm.dsName = row.dsName
      // this.jdbcConfigsForm.dsDesc = row.dsDesc
      // this.jdbcConfigsForm.dsType = row.dsType
      // this.jdbcConfigsForm.dsDriver = row.dsDriver
      // this.jdbcConfigsForm.dsUrl = row.dsUrl
      // this.jdbcConfigsForm.dsUsername = row.dsUsername
      // this.jdbcConfigsForm.dsPassword = row.dsPassword
      let arr = []
      row.dictSubjects.map(val => {
        arr.push([val.subjectType, val.id])
      })
      this.jdbcConfigsForm.dictSubjects = arr
      this.jdbcConfigsFormVisible = true
      console.log(this.jdbcConfigsForm)
    },
    delJdbcConfigs (id) {
      let that = this
      this.$commonFunc.message({type: 'confirm', message: '您确定要删除该数据吗?'}, function () {
        that.axios.delete('/jdbcconfigs/' + id).then(res => {
          if (res.status === 200) {
            that.$commonFunc.message({type: 'success', message: '删除成功'})
            that.getJdbcConfigs(1, that.jdbcConfigsPageSize, that.jdbcConfigsSort)
          } else {
            that.$commonFunc.message({type: 'error', message: res.statusText})
          }
        })
      })
    },
    // 测试还是提交 isTest 是否是测试 默认是false
    submitJdbcConfigs (isTest) {
      let dictSubjects = []
      this.jdbcConfigsForm.dictSubjects.map(val => {
        dictSubjects.push({id: val[val.length - 1]})
      })
      this.$refs.jdbcConfigs.validate((valid) => {
        if (valid) {
          let url = ''
          let tip = ''
          let method = ''
          let data = {}
          if (this.jdbcConfigsForm.id === '') { // 添加
            url = '/jdbcconfigs'
            tip = '添加成功'
            method = 'post'
            data = {
              dsName: this.jdbcConfigsForm.dsName,
              dsDesc: this.jdbcConfigsForm.dsDesc,
              dsType: this.jdbcConfigsForm.dsType,
              dsDriver: this.jdbcConfigsForm.dsDriver,
              dsUrl: this.jdbcConfigsForm.dsUrl,
              dsUsername: this.jdbcConfigsForm.dsUsername,
              dsPassword: this.jdbcConfigsForm.dsPassword,
              dictSubjects: dictSubjects
            }
          } else {
            url = '/jdbcconfigs/' + this.jdbcConfigsForm.id
            tip = '编辑成功'
            method = 'put'
            for(let key in this.jdbcConfigsForm){
              data[key] = this.jdbcConfigsForm[key]
            }
            data.dictSubjects = dictSubjects
          }
          if (isTest) { // 测试连接
            url = '/jdbcconfigs/connection'
            method = 'post'
          }
          this.axios({
            method: method,
            url: url,
            data: data
          }).then(res => {
            if (isTest) { // 测试连接
              if (res.data) {
                this.$commonFunc.message({type: 'success', message: '测试连接成功'})
                console.log(this.jdbcConfigsForm)
              } else {
                this.$commonFunc.message({type: 'error', message: '测试连接失败'})
              }
            } else { // 提交
              if (res.status === 200) {
                this.$commonFunc.message({type: 'success', message: tip})
                this.getJdbcConfigs(1, this.jdbcConfigsPageSize, this.jdbcConfigsSort)
                this.jdbcConfigsFormVisible = false
              } else {
                this.$commonFunc.message({type: 'error', message: res.statusText})
              }
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 测试连接
    testConnection () {
      this.submitJdbcConfigs(true)
    },
    // 格式化分类分级状态
    formatterState (row, column, cellValue, index) {
      if (cellValue === 'notstart') {
        return "<span style='color: #8c939d'>未开始</span>"
      } else if (cellValue === 'classifying' || cellValue === 'classified') {
        return '<span style="color: darkred">分类中</span>'
      } else if (cellValue === 'evaluating') {
        return '<span style="color: darkred">评价中</span>'
      } else if (cellValue === 'grading' || cellValue === 'graded') {
        return '<span style="color: darkred">分级中</span>'
      } else if (cellValue === 'finished') {
        return '<span style="color: blue">已完成</span>'
      }
    },
    // 格式化主题
    formatterSubject (row, column, cellValue, index) {
      let arr = []
      row.dictSubjects.map(val => {
        arr.push(val.subjectName)
      })
      return arr.join(' , ')
    },
    // 详情 name:数据名称
    goDetail (row) {
      this.jdbcconfigId = row.id
      this.jdbcconfigIdClassificationTime = row.classificationTime
      // this.fullScreenLoading = true
      this.showLoading()
      this.detailName = row.dsName
      this.isDetailPage = true
      this.getInstances(row.id) // 获取分级数据
      this.getSecurityIndicators('indicatorCode') // 获取安全指标
      this.getStates(row.id) // 获取状态
    },
    goBack () {
      this.detailName = ''
      this.isDetailPage = false
      clearTimeout(this.jdbcconfigIdStatesTimer)
    },
    // 获取分类维护by dsID
    getInstances (jdbcconfigId) {
      this.axios.get('/ontologys/'+jdbcconfigId+'/instances').then(res => {
        this.hideLoading()
        this.instancesTree = res.data || []
        this.treeEchart('', this.instancesTree)
      })
    },
    changeCurInstances (val, node) {
      this.curInstancesNode = val
      if (val.type === 'Entity' && node.isLeaf) {
        this.showLoading()
        this.axios.get('/ontologys/'+this.jdbcconfigId+'/instances/' + val.id).then(res => {
          this.hideLoading()
          node.data.children = res.data
        })
      } else if (val.type === 'Category') {
        this.getProperties() // 获取数据分级
      }
    },
    // 选择添加主题或者分类
    selectInstancesType (command) {
      if (command === 'subject') { // 主题
        this.$refs.instancesTree.setCurrentKey(null)
        this.curInstancesNode = null
        this.instancesForm.parentId = ''
        this.instancesForm.parentName = ''
      } else {
        if (!this.curInstancesNode) {
          this.$commonFunc.message({type: 'warning', message: '请选择一个主题'})
          return false
        } else if(this.curInstancesNode.type === 'Subject') {
          this.instancesForm.parentId = this.curInstancesNode.id
          this.instancesForm.parentName = this.curInstancesNode.name
        } else {
          this.$commonFunc.message({type: 'warning', message: '必须选择主题'})
          return false
        }
      }
      this.addInstances()
    },
    addInstances () {
      if (this.$refs.instancesForm) {
        this.$refs.instancesForm.resetFields()
      }
      this.instancesForm.id = ''
      this.instancesForm.instanceName = ''
      this.instancesFormVisible = true
    },
    editInstances (node) {
      if (this.$refs.instancesForm) {
        this.$refs.instancesForm.resetFields()
      }
      this.instancesForm.id = node.data.id
      this.instancesForm.instanceName = node.data.name
      this.instancesForm.parentName = node.parent.data.name
      this.instancesForm.parentId = node.parent.data.id
      this.instancesFormVisible = true
    },
    delInstances (node) {
      let that = this
      // let type = ''
      // if (node.type === 'Subject') {
      //   type = 'Subject'
      // } else {
      //   type = 'Category'
      // }
      this.$commonFunc.message({type: 'confirm', message: '您确定要删除该数据吗?'}, function () {
        that.axios.delete('/ontologys/' + that.jdbcconfigId + '/instances/' + node.id + '?className=' + node.type).then(res => {
          if (res.status === 200) {
            that.$commonFunc.message({type: 'success', message: '删除成功'})
            that.getInstances(that.jdbcconfigId)
            that.curInstancesNode == null
            if (node.type === 'Subject') {
              that.instancesForm.parentName = ''
              that.instancesForm.parentId = ''
            }
          } else {
            that.$commonFunc.message({type: 'error', message: res.statusText})
          }
        })
      })
    },
    submitInstances (isDrag) {
      let method = ''
      let url = ''
      let tip = ''
      let data = null
      if (this.instancesForm.id === '') { // 添加
        method = 'post'
        url = '/ontologys/' + this.jdbcconfigId + '/instances'
        tip = '添加成功'
      } else { // 编辑
        method = 'put'
        url = '/ontologys/' + this.jdbcconfigId + '/instances/' + this.instancesForm.id
        tip = '编辑成功'
      }
      if (isDrag) {
        data = {className: this.instancesForm.className, belongsToInstanceId: this.instancesForm.parentId}
      } else {
        if (this.instancesForm.parentId === '') { // 主题
          data = {className: 'Subject', instanceName: this.instancesForm.instanceName}
        } else { // 分类
          data = {className: 'Category', instanceName: this.instancesForm.instanceName, subjectId: this.instancesForm.parentId}
        }
      }
      this.axios({
        method: method,
        url: url,
        data: this.qs.stringify(data)
      }).then(res => {
        if (res.status === 200) {
          this.$commonFunc.message({type: 'success', message: tip})
          this.getInstances(this.jdbcconfigId)
          this.instancesFormVisible = false
        } else {
          this.$commonFunc.message({type: 'error', message: res.statusText})
        }
      })
    },
    // 判断节点是否能够拖拽
    allowDragInstances (node) {
      if (node.data.type === 'Entity' || node.data.type === 'Category') {
        return true
      } else {
        return false
      }
    },
    allowDropInstances (draggingNode, dropNode, type) {
      if (((draggingNode.data.type === 'Entity' && dropNode.data.type === 'Category') ||
            (draggingNode.data.type === 'Category' && dropNode.data.type === 'Subject')) && type === 'inner') {
        return true
      } else {
        return false
      }
    },
    nodeDropInstances (draggingNode, dropNode, dropType, ev) {
      this.instancesForm.id = draggingNode.data.id
      this.instancesForm.className = draggingNode.data.type
      this.instancesForm.parentId = dropNode.data.id
      this.submitInstances(true)
    },
    // 节点全部展开
    unFoldAll () {
      this.isOpenAll = true
      let self = this;
      // 将没有转换成树的原数据
      let treeList = this.instancesTree;
      for (let i = 0; i < treeList.length; i++) {
        // 将没有转换成树的原数据设置key为... 的展开
        self.$refs.instancesTree.store.nodesMap[treeList[i].id].expanded = true
      }
    },
    // 节点全部折叠
    collapseAll () {
      this.isOpenAll = false
      let self = this;
      let treeList = this.instancesTree;
      for (let i = 0; i < treeList.length; i++) {
        self.$refs.instancesTree.store.nodesMap[treeList[i].id].expanded = false
      }
    },
    // instancesId 用于刷新图激活状态
    treeEchart (instancesId, treeData) {
      let data = {name: this.detailName, children: []}
      // treeData.map(val => {
      //   data.children.push(val)
      // })
      data.children = treeData
      // 递归遍历节点
      function eachData (node, parentID) {
        if (node.children && node.children.length > 0) {
          node.children.map(val => {
            if (parentID) {
              val.parentId = parentID
            }
            // 设置节点的和文字颜色
            if (val.securityLevel || val.id === instancesId) {
              let color = ''
              if (val.securityLevel === '公开级') {
                color = '#67C23A'
              } else if (val.securityLevel === '普通商秘级') {
                color = '#E6A23C'
              } else if (val.securityLevel === '核心商秘级') {
                color = '#F56C6C'
              } else {
                color = '#409EFF'
              }
              val.itemStyle = {
                color: color,
                borderColor: color
              }
              val.label = {
                color: color
              }
              // val.lineStyle = {
              //   color: '#0000ff',
              //   borderColor: '#0000ff'
              // }
            }
            if (val.type === 'Category' && val.collapsed !== '') {
              val.collapsed = true
            }
            // if (val.type === 'Entity' && val.children === null) {
            //   // val.children = [{name: ''}]
            //   // console.log(val)
            // }
            if (val.children) {
              eachData(val, val.id)
            }
          })
        }
      }
      eachData(data, '')
      // console.log(this.instancesTree)
      this.$nextTick(() => {
        let myEchart  =this.$echarts.init(document.getElementById('treeEchart'))
        let option = {
          tooltip: {
            trigger: 'item',
            triggerOn: 'mousemove'
          },
          series: [
            {
              type: 'tree',
              roam: true,
              // move: false,
              data: [data],
              initialTreeDepth: 4,
              // itemStyle: {
              //   color: '#ff0000'
              // },
              top: '2%',
              left: '10%',
              bottom: '2%',
              right: '20%',
              symbolSize: 7,
              label: {
                position: 'top',
                verticalAlign: 'middle',
                align: 'center',
                fontSize: 12,
                formatter: function (params) {
                  return params.data.desc
                  // return '{<a>'+params.data.name+'</a>}'
                  // console.log(params)
                },
                triggerEvent : true
              },
              leaves: {
                label: {
                  position: 'right',
                  verticalAlign: 'middle',
                  align: 'left'
                }
              },
              tooltip: {
                show: false
                // position: 'inside',
                // // position: ['50%', '50%'],
                // // triggerOn: 'click',   //触发方式
                // enterable: true, // 鼠标可移入tooltip中
                // formatter: function (params) {
                //   let e = event || window.event
                //   console.log(e.pageX)
                //   // console.log('-----')
                //   let dom = document.getElementById('myTips')
                //   if (dom) {
                //     document.getElementById('myTips').remove()
                //   }
                //   var o=document.createElement('span')
                //   o.id = 'myTips'
                //   o.style.position = 'absolute'
                //   o.style.zIndex = 9999
                //   o.style.left = e.clientX + 'px'
                //   o.style.top = e.clientY + 'px'
                //   o.style.background = '#000'
                //   o.style.color = '#fff'
                //   o.innerHTML = params.data.name
                //   document.body.appendChild(o)
                //   // document.body.appendChild('<span id="myTips" style="position:fixed;z-index: 9999;left:'+e.pageX+'px;top:'+e.pageY+'px;background:#000;color:#fff;">'+params.data.name+'</span>')
                //   console.log(params)
                //   // return '<span style="color:red;" onclick="myClick()">'+params.data.name+'</span>'
                // }
              },
              expandAndCollapse: true,
              animationDuration: 550,
              animationDurationUpdate: 750
            }
          ]
        }
        let that = this
        myEchart.setOption(option)
        myEchart.off('click')
        myEchart.on('click', function (params) {
          console.log(params)
          if (params.data.type === 'Entity') {
            if (params.data.children === null || params.data.children[0].name ==='') {
              that.showLoading()
              that.axios.get('/ontologys/'+that.jdbcconfigId+'/instances/' + params.data.id).then(res => {
                that.hideLoading()
                params.data.children = res.data
                params.data.collapsed = !params.data.collapsed
                eachData(params.data, '')
                let option = myEchart.getOption()
                for (let i = 0; i < option.series[0].data[0].children.length; i++) { // subject
                  let item = option.series[0].data[0].children[i]
                  let isFind = false
                  for (let j = 0; j < item.children.length; j++) { // category
                    let subItem = item.children[j]
                    if (params.data.parentId === subItem.id) {
                      subItem.collapsed = ''
                      isFind = true
                      // console.log(subItem)
                      break
                    }
                  }
                  if (isFind) {
                    break
                  }
                }
                // console.log(option)
                option.animation = false
                myEchart.clear()
                myEchart.setOption(option)
              })
            } else {
              params.data.collapsed = !params.data.collapsed
              // console.log()
            }
          } else if (params.data.type === 'Category') {
            params.data.children.map(val => {
              val.children = [{name: '', value: ''}]
              val.collapsed = true
            })
            params.data.collapsed = !params.data.collapsed
            let option = myEchart.getOption()
            option.animation = false
            myEchart.clear()
            myEchart.setOption(option)
          }
        })
        // myEchart.on('click', 'series.tree', e =>
        //   console.log(e)
        // )
      })
    },
    /*
    * 获取安全指标
    * 参数 sort 排序（column,desc）
    * */
    getSecurityIndicators (sort) {
      this.questionnaireList = []
      this.axios.get('/securityindicators?getType=all&sort=' + sort).then(res => {
        if (res.status === 200) {
          let dimension = ''
          res.data.map((item, index) => {
            let indicatorValue = item.indicatorValue.split('|')
            if (item.indicatorDimension !== dimension) {
              dimension = item.indicatorDimension
              let obj = {}
              obj.indicatorDimension = item.indicatorDimension
              if (item.indicatorDimension === 'confidentiality') {
                obj.indicatorDimensionName = '保密性'
              } else if (item.indicatorDimension === 'integrity') {
                obj.indicatorDimensionName = '完整性'
              } else if (item.indicatorDimension === 'availability') {
                obj.indicatorDimensionName = '可用性'
              }
              obj.checkedIndicatorValue = ''
              obj.summaryList = ['低', '中', '高']
              obj.type = 'indicator'
              if (this.questionnaireList.length > 0) {
                obj.isOpen = false
              } else {
                obj.isOpen = true
              }
              obj.children = []
              this.questionnaireList.push(obj)
              this.propertiesSubmitData[item.indicatorDimension] = ''
            }
            this.questionnaireList[this.questionnaireList.length - 1].children.push({indicatorName: item.indicatorName, id: item.id, indicatorValue: indicatorValue, indicatorCode: item.indicatorCode, checkedIndicatorValue: ''})
            this.propertiesSubmitData[item.indicatorCode] = ''
          })
        } else {
          this.$commonFunc.message({type: 'error', message: res.statusText})
        }
        this.getSecurityLevels('levelSeq') // 获取安全等级
      })
    },
    // 获取安全等级
    getSecurityLevels (sort) {
      this.axios.get('/securitylevels?getType=all&sort=' + sort).then(res => {
        if (res.status === 200) {
          this.questionnaireList.push({indicatorDimension: 'securityLevel', indicatorDimensionName: '安全等级', summaryList: [], type: 'levels', checkedIndicatorValue: ''})
          res.data.map(val => {
            this.questionnaireList[this.questionnaireList.length - 1].summaryList.push(val)
          })
          this.propertiesSubmitData['securityLevel'] = ''
          // console.log(this.propertiesSubmitData)
        } else {
          this.$commonFunc.message({type: 'error', message: res.statusText})
        }
      })
    },
    // 点击获取数据评价
    getProperties() {
      this.showLoading()
      this.axios.get('/ontologys/' + this.jdbcconfigId + '/instances/' + this.curInstancesNode.id + '/properties').then(res => {
        this.hideLoading()
        if (res.status === 200) {
          this.propertiesSubmitData = {}
          // this.isSubmitProperties = true
          let obj = {}
          if (res.data.securityLevel) { // 有数据
            this.isSubmitProperties = true
            for (let key in res.data) {
              if (key !== 'id' && key !== 'name' && key !== 'desc') {
                obj[key] = res.data[key]
              }
            }
            this.propertiesSubmitData = obj
          } else { // 无数据
            this.isSubmitProperties = false
          }
        }
      })
    },
    submitProperties () {
      if (!this.curInstancesNode) {
        this.$commonFunc.message({type: 'warning', message: '请选择数据分类'})
        return false
      }
      let isAllChecked = true
      for (let key in this.propertiesSubmitData) {
        if (this.propertiesSubmitData[key] === '') {
          isAllChecked = false
          break
        }
      }
      if (isAllChecked) {
        let method = ''
        if (this.isSubmitProperties) {
          method = 'put'
        } else {
          method = 'post'
        }
        this.showLoading()
        this.axios({
          method: method,
          url: '/ontologys/' + this.jdbcconfigId + '/instances/' + this.curInstancesNode.id + '/properties',
          data: this.propertiesSubmitData
        }).then(res => {
          this.hideLoading()
          if (res.status === 200) {
            this.$commonFunc.message({type: 'success', message: '成功'})
            if (!this.isSubmitProperties) {
              this.treeEchart(this.curInstancesNode.id, this.instancesTree)
            }
          } else {
            this.$commonFunc.message({type: 'error', message: res.statusText})
          }
        })
      } else {
        this.$commonFunc.message({type: 'error', message: '您有未选项'})
      }
    },
    // 遍历问卷
    eachQuestionnaireList (data) {
      data.map(val => {
        this.propertiesSubmitData[val.indicatorDimension || val.indicatorCode] = val.checkedIndicatorValue
        if (val.children) {
          this.eachQuestionnaireList(val.children)
        }
      })
    },
    questionnaireIsOpen (index) {
      this.questionnaireList[index].isOpen = !this.questionnaireList[index].isOpen
    },
    /*
     * 分级分类相关操作
     * */
    // 获取状态
    getStates(jdbcconfigId) {
      clearTimeout(this.jdbcconfigIdStatesTimer)
      this.axios.get('/ontologys/' + jdbcconfigId + '/states').then(res => {
        if (res.status === 200) {
          this.jdbcconfigIdStates = res.data
          if (res.data === 'notstart') {
            this.jdbcconfigIdStatesNumber = 1
          } else if (res.data === 'classifying' || res.data === 'classified') {
            this.jdbcconfigIdStatesNumber = 2
          } else if (res.data === 'evaluating') {
            this.jdbcconfigIdStatesNumber = 3
          } else if (res.data === 'grading' || res.data === 'graded') {
            this.jdbcconfigIdStatesNumber = 4
          } else { // finished
            this.jdbcconfigIdStatesNumber = 5
            //this.getSecurityIndicators('indicatorCode') // 获取安全指标
            //更新完成时间
            this.axios.get('/jdbcconfigs/' + this.jdbcconfigId).then(res => {
              if (res.status === 200) {
                this.jdbcconfigIdClassificationTime = res.data.classificationTime
                for (let key in this.tableData) {
                  if (this.tableData[key].id === this.jdbcconfigId) {
                    this.tableData[key].classificationTime = res.data.classificationTime
                    this.tableData[key].classificationState =  res.data.classificationState
                    break
                  }
                }
              }
            })
          }
          if (res.data == 'classifying' || res.data === 'grading') {
            let that = this
            this.jdbcconfigIdStatesTimer = setTimeout(() => {
              that.getStates(jdbcconfigId)
            }, 2000)
          }
          if (res.data === 'classified') {
            this.getInstances(this.jdbcconfigId) // 获取分类
          }
        }
      })
    },
    // 提交状态
    submitStates (action) {
      let method = ''
      if (action === 'beginClassification') {
        method = 'post'
      } else {
        method = 'put'
      }
      this.axios({
        method: method,
        url: '/ontologys/' + this.jdbcconfigId + '/states',
        data: this.qs.stringify({action: action})
      }).then(res => {
        if (res.status === 200) {
          if(res.data && res.data != true && res.data != false) {
            this.$commonFunc.message({type: 'error', message: res.data})
          }
          if (action !== 'finished') {
            this.getStates(this.jdbcconfigId)
          }
        }
      })
    },
    // 显示加载中
    showLoading () {
      this.fullScreenLoading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, 0.5)'
      })
    },
    // 隐藏加载中
    hideLoading () {
      this.fullScreenLoading.close()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    }
  }
}
</script>

<style>
  .questionnaireWrapper{
    border-left:1px solid #EBEEF5;
    padding-left:15px;
  }
  .questionnaire .el-radio__label{
    font-size:12px;
    font-weight: normal;
  }
  .questionnaire .questionnaireRadio{
    padding:10px 0px;
  }
  .questionnaire .questionnaireRadio .el-radio{
    width:80px;
    margin-right:0px;
  }
  .questionnaire .questionnaireItemSummary{
    margin-top:5px;
    margin-bottom:15px;
    color:#e6a23c;
  }
  .questionnaire .questionnaireItemSummary .el-radio{
    margin-right: 10px;
  }
  .questionnaire .questionnaireItem{
    overflow: hidden;
    -webkit-transition: height 0.5s;
    -moz-transition: height 0.5s;
    -ms-transition: height 0.5s;
    -o-transition: height 0.5s;
    transition: height 0.5s;
  }
  .questionnaireTitle{
    cursor: pointer;
    font-size:16px;
  }
  .questionnaireTitle i{
    font-size:16px;
    margin-top:5px;
  }
  /*.questionnaireSummary .el-radio__label{*/
    /*font-size:12px;*/
    /*font-weight: normal;*/
  /*}*/
  /*.questionnaireSummary .el-radio{*/
    /*margin-right:10px;*/
  /*}*/
  /*.questionnaireSummary .questionnaireSummaryTitle{*/
    /*!*padding-left:20px;*!*/
    /*padding-top:15px;*/
    /*padding-bottom:15px;*/
    /*color:#f56c6c;*/
    /*font-size:18px;*/
    /*text-align: center;*/
  /*}*/
</style>
<style scoped>

</style>
